import React, { useState, useRef } from 'react';
import { Form, Input, Button, Table, Card, Empty, message, Modal, Spin } from 'antd';
import { SearchOutlined, RobotOutlined, EditOutlined, SaveOutlined, CloseOutlined, FileWordOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import { Document, Paragraph, TextRun, HeadingLevel, AlignmentType, Packer } from 'docx';
import { saveAs } from 'file-saver';
import request from '../utils/request';

const { TextArea } = Input;

const StudentQueryPage = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [searched, setSearched] = useState(false);
  const [queryType, setQueryType] = useState('name'); // 'name' 或 'class'
  const [averages, setAverages] = useState({}); // 存储各科平均分
  const [analysisModalVisible, setAnalysisModalVisible] = useState(false);
  const [analysisLoading, setAnalysisLoading] = useState(false);
  const [analysisReport, setAnalysisReport] = useState('');
  const [currentStudent, setCurrentStudent] = useState(null);
  const [reportFromCache, setReportFromCache] = useState(false);
  const [reportCachedAt, setReportCachedAt] = useState(null);
  const [isEditing, setIsEditing] = useState(false);
  const [editedReport, setEditedReport] = useState('');
  const [exportingPdf, setExportingPdf] = useState(false);
  const reportContentRef = useRef(null);

  // 计算各科平均分
  const calculateAverages = (records) => {
    const subjects = ['chinese', 'math', 'english', 'physics', 'chemistry', 'biology', 'politics', 'history', 'geography', 'totalScore'];
    const avgs = {};
    
    subjects.forEach(subject => {
      const validScores = records
        .map(r => r[subject])
        .filter(score => score !== null && score !== undefined && score !== '');
      
      if (validScores.length > 0) {
        const sum = validScores.reduce((acc, score) => acc + parseFloat(score), 0);
        avgs[subject] = (sum / validScores.length).toFixed(2);
      } else {
        avgs[subject] = '-';
      }
    });
    
    setAverages(avgs);
  };

  const handleSearch = async () => {
    try {
      const values = await form.validateFields();
      
      let searchValue = values.searchValue?.trim();
      if (!searchValue) {
        message.warning(queryType === 'name' ? '请输入姓名' : '请输入班级名称');
        return;
      }

      // 如果是按班级查询，支持简写输入
      if (queryType === 'class') {
        // 如果只输入数字，自动补全为"高一年级X班"
        if (/^\d+$/.test(searchValue)) {
          searchValue = `高一年级${searchValue}班`;
          message.info(`正在查询：${searchValue}`);
        }
      }

      setLoading(true);
      setSearched(true);

      // 使用公开 API，不需要 token
      const params = {
        pageSize: 1000 // 增加到1000，支持查询整个班级
      };

      if (queryType === 'name') {
        params.name = searchValue;
      } else {
        params.className = searchValue;
      }

      const response = await request.get('/public/scores', {
        params
      });

      if (response.success) {
        setData(response.data.records);
        if (response.data.records.length === 0) {
          message.info('未找到相关成绩记录');
        } else {
          // 计算各科平均分
          calculateAverages(response.data.records);
        }
      }
    } catch (error) {
      // 错误已在 request.js 中处理
      setData([]);
    } finally {
      setLoading(false);
    }
  };

  // 处理班级名称点击事件
  const handleClassClick = async (className) => {
    // 切换到班级查询模式
    setQueryType('class');
    
    // 设置表单值
    form.setFieldsValue({ searchValue: className });
    
    // 执行查询
    setLoading(true);
    setSearched(true);
    
    try {
      const response = await request.get('/public/scores', {
        params: {
          className: className,
          pageSize: 1000
        }
      });
      
      if (response.success) {
        setData(response.data.records);
        
        // 计算各科平均分
        calculateAverages(response.data.records);
        
        if (response.data.records.length === 0) {
          message.info('未找到相关成绩记录');
        }
      }
    } catch (error) {
      // 错误已在 request.js 中处理
      setData([]);
      message.error('查询失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理学生姓名点击事件
  const handleNameClick = async (name) => {
    // 切换到姓名查询模式
    setQueryType('name');
    
    // 设置表单值
    form.setFieldsValue({ searchValue: name });
    
    // 执行查询
    setLoading(true);
    setSearched(true);
    
    try {
      const response = await request.get('/public/scores', {
        params: {
          name: name,
          pageSize: 1000
        }
      });
      
      if (response.success) {
        setData(response.data.records);
        
        // 计算各科平均分
        calculateAverages(response.data.records);
        
        if (response.data.records.length === 0) {
          message.info('未找到相关成绩记录');
        }
      }
    } catch (error) {
      // 错误已在 request.js 中处理
      setData([]);
      message.error('查询失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 保存编辑的报告
  const handleSaveReport = async () => {
    try {
      if (!editedReport.trim()) {
        message.warning('报告内容不能为空');
        return;
      }

      setAnalysisLoading(true);

      const response = await request.post('/public/analysis/update', {
        name: currentStudent.name,
        className: currentStudent.className,
        report: editedReport
      });

      if (response.success) {
        setAnalysisReport(editedReport);
        setIsEditing(false);
        message.success('报告保存成功');
      }
    } catch (error) {
      message.error('保存失败，请稍后重试');
    } finally {
      setAnalysisLoading(false);
    }
  };

  // 导出Word文档
  const handleExportWord = async () => {
    if (!analysisReport || !currentStudent) {
      message.error('无法导出文档，请稍后重试');
      return;
    }

    try {
      setExportingPdf(true);
      message.loading({ content: '正在生成Word文档，请稍候...', key: 'word-export', duration: 0 });

      // 解析Markdown并转换为Word段落
      const parseMarkdownToDocx = (markdown) => {
        const lines = markdown.split('\n');
        const paragraphs = [];
        
        for (let i = 0; i < lines.length; i++) {
          const line = lines[i].trim();
          
          if (!line) {
            // 空行，添加空段落
            paragraphs.push(new Paragraph({ text: '' }));
            continue;
          }
          
          // 一级标题
          if (line.startsWith('# ')) {
            paragraphs.push(
              new Paragraph({
                text: line.substring(2),
                heading: HeadingLevel.HEADING_1,
                spacing: { before: 400, after: 200 }
              })
            );
          }
          // 二级标题
          else if (line.startsWith('## ')) {
            paragraphs.push(
              new Paragraph({
                text: line.substring(3),
                heading: HeadingLevel.HEADING_2,
                spacing: { before: 300, after: 150 }
              })
            );
          }
          // 三级标题
          else if (line.startsWith('### ')) {
            paragraphs.push(
              new Paragraph({
                text: line.substring(4),
                heading: HeadingLevel.HEADING_3,
                spacing: { before: 200, after: 100 }
              })
            );
          }
          // 列表项
          else if (line.startsWith('- ') || line.startsWith('* ')) {
            const text = line.substring(2);
            // 处理粗体
            const parts = text.split(/(\*\*.*?\*\*)/g);
            const children = parts.map(part => {
              if (part.startsWith('**') && part.endsWith('**')) {
                return new TextRun({ text: part.slice(2, -2), bold: true });
              }
              return new TextRun({ text: part });
            });
            
            paragraphs.push(
              new Paragraph({
                children,
                bullet: { level: 0 },
                spacing: { before: 100, after: 100 }
              })
            );
          }
          // 数字列表
          else if (/^\d+\.\s/.test(line)) {
            const text = line.replace(/^\d+\.\s/, '');
            const parts = text.split(/(\*\*.*?\*\*)/g);
            const children = parts.map(part => {
              if (part.startsWith('**') && part.endsWith('**')) {
                return new TextRun({ text: part.slice(2, -2), bold: true });
              }
              return new TextRun({ text: part });
            });
            
            paragraphs.push(
              new Paragraph({
                children,
                numbering: { reference: 'default-numbering', level: 0 },
                spacing: { before: 100, after: 100 }
              })
            );
          }
          // 普通段落
          else {
            // 处理粗体和斜体
            const parts = line.split(/(\*\*.*?\*\*|\*.*?\*)/g);
            const children = parts.map(part => {
              if (part.startsWith('**') && part.endsWith('**')) {
                return new TextRun({ text: part.slice(2, -2), bold: true });
              } else if (part.startsWith('*') && part.endsWith('*')) {
                return new TextRun({ text: part.slice(1, -1), italics: true });
              }
              return new TextRun({ text: part });
            });
            
            paragraphs.push(
              new Paragraph({
                children,
                spacing: { before: 100, after: 100 },
                alignment: AlignmentType.JUSTIFIED
              })
            );
          }
        }
        
        return paragraphs;
      };

      // 创建Word文档
      const doc = new Document({
        sections: [{
          properties: {},
          children: [
            // 标题
            new Paragraph({
              text: 'AI 智能成绩分析报告',
              heading: HeadingLevel.TITLE,
              alignment: AlignmentType.CENTER,
              spacing: { after: 200 }
            }),
            // 学生信息
            new Paragraph({
              children: [
                new TextRun({ text: `学生：${currentStudent.name}`, bold: true }),
                new TextRun({ text: ' | ' }),
                new TextRun({ text: `班级：${currentStudent.className}`, bold: true })
              ],
              alignment: AlignmentType.CENTER,
              spacing: { after: 100 }
            }),
            new Paragraph({
              text: `生成时间：${new Date().toLocaleString('zh-CN')}`,
              alignment: AlignmentType.CENTER,
              spacing: { after: 400 }
            }),
            // 分隔线（使用空段落）
            new Paragraph({ text: '', spacing: { after: 200 } }),
            // 报告内容
            ...parseMarkdownToDocx(analysisReport)
          ]
        }]
      });

      // 生成并下载Word文档
      const blob = await Packer.toBlob(doc);
      const filename = `${currentStudent.name}_成绩分析报告_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.docx`;
      saveAs(blob, filename);
      
      message.success({ content: 'Word文档导出成功！', key: 'word-export', duration: 2 });
    } catch (error) {
      console.error('Word导出错误:', error);
      message.error({ content: 'Word导出失败，请稍后重试', key: 'word-export', duration: 2 });
    } finally {
      setExportingPdf(false);
    }
  };

  // 生成AI分析报告（流式输出版本）
  const handleGenerateAnalysis = async (studentName, className, forceRefresh = false) => {
    try {
      setCurrentStudent({ name: studentName, className });
      setAnalysisModalVisible(true);
      setAnalysisLoading(true);
      setAnalysisReport('');
      setReportFromCache(false);
      setReportCachedAt(null);
      setIsEditing(false);

      // 使用 fetch API 接收流式数据
      // 动态获取API地址（与request.js保持一致）
      const getApiBaseUrl = () => {
        if (process.env.NODE_ENV === 'production') {
          const protocol = window.location.protocol;
          const hostname = window.location.hostname;
          return `${protocol}//${hostname}:7661/api`;
        }
        return process.env.REACT_APP_API_BASE_URL || 'http://localhost:7661/api';
      };
      
      const baseURL = getApiBaseUrl();
      console.log('[流式] 开始请求:', `${baseURL}/public/analysis/stream`);
      
      const response = await fetch(`${baseURL}/public/analysis/stream`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: studentName,
          className: className || '',
          forceRefresh: forceRefresh
        })
      });

      console.log('[流式] 响应状态:', response.status, response.headers.get('content-type'));

      if (!response.ok) {
        throw new Error('请求失败');
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let reportContent = '';
      let buffer = '';
      let chunkCount = 0;

      console.log('[流式] 开始读取数据流...');

      while (true) {
        const { done, value } = await reader.read();
        
        if (done) {
          console.log('[流式] 数据流结束，共收到', chunkCount, '个块');
          break;
        }

        // 解码数据块
        buffer += decoder.decode(value, { stream: true });
        
        // 按行分割
        const lines = buffer.split('\n');
        buffer = lines.pop() || ''; // 保留最后一个不完整的行
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const data = JSON.parse(line.slice(6));
              console.log('[流式] 收到数据:', data.type, data.content?.substring(0, 50));
              
              if (data.type === 'cache') {
                // 使用缓存的报告
                console.log('[流式] 使用缓存报告');
                reportContent = data.content;
                setAnalysisReport(reportContent);
                setReportFromCache(true);
                setReportCachedAt(data.cachedAt);
                setAnalysisLoading(false);
                message.success('已加载缓存的分析报告');
                return;
              } else if (data.type === 'chunk') {
                // 流式接收内容
                chunkCount++;
                reportContent += data.content;
                setAnalysisReport(reportContent);
                console.log('[流式] 累计内容长度:', reportContent.length);
              } else if (data.type === 'done') {
                // 生成完成
                console.log('[流式] 生成完成');
                setAnalysisLoading(false);
                message.success('分析报告生成成功！');
                return;
              } else if (data.type === 'error') {
                // 错误处理
                console.error('[流式] 错误:', data.message);
                setAnalysisLoading(false);
                message.error(data.message || '生成分析报告失败');
                setAnalysisModalVisible(false);
                return;
              }
            } catch (e) {
              console.error('[流式] 解析SSE数据失败:', e, line);
            }
          }
        }
      }
      
      // 流结束
      setAnalysisLoading(false);
      
    } catch (error) {
      console.error('AI分析错误:', error);
      setAnalysisLoading(false);
      
      let errorMessage = '生成分析报告失败';
      if (error.message?.includes('Failed to fetch')) {
        errorMessage = '网络连接失败，请检查网络连接后重试';
      } else if (error.message) {
        errorMessage = error.message;
      }
      
      message.error(errorMessage);
      setAnalysisModalVisible(false);
    }
  };

  // 自定义排序函数，处理空值
  // 空值始终排在最后，无论升序还是降序
  const createSorter = (field) => (a, b, sortOrder) => {
    const valA = a[field];
    const valB = b[field];
    
    const isEmptyA = valA === null || valA === undefined || valA === '';
    const isEmptyB = valB === null || valB === undefined || valB === '';
    
    // 如果两个都是空值，保持原顺序
    if (isEmptyA && isEmptyB) return 0;
    
    // 如果A是空值，A排在后面（返回正数）
    if (isEmptyA) return 1;
    
    // 如果B是空值，B排在后面（返回负数）
    if (isEmptyB) return -1;
    
    // 两个都有值，正常比较
    return parseFloat(valA) - parseFloat(valB);
  };

  const columns = [
    {
      title: '准考证号',
      dataIndex: 'studentId',
      key: 'studentId',
      width: 120
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      render: (name, record) => (
        <a 
          onClick={() => queryType === 'name' 
            ? handleGenerateAnalysis(name, record.className)
            : handleNameClick(name)
          }
          style={{ color: '#1890ff', cursor: 'pointer' }}
          title={queryType === 'name' ? '点击查看AI智能分析' : '点击查看该学生所有成绩'}
        >
          {name}
        </a>
      )
    },
    {
      title: '班级',
      dataIndex: 'className',
      key: 'className',
      width: 120,
      render: (className, record) => (
        queryType === 'name' ? (
          <a 
            onClick={() => handleClassClick(className)}
            style={{ color: '#1890ff', cursor: 'pointer' }}
            title="点击查看班级成绩"
          >
            {className}
          </a>
        ) : className
      )
    },
    {
      title: '考试名称',
      dataIndex: 'examName',
      key: 'examName',
      width: 150
    },
    {
      title: '考试日期',
      dataIndex: 'examDate',
      key: 'examDate',
      width: 120
    },
    {
      title: '语文',
      dataIndex: 'chinese',
      key: 'chinese',
      width: 80,
      sorter: queryType === 'class' ? createSorter('chinese') : false,
      render: (val) => val || '-'
    },
    {
      title: '数学',
      dataIndex: 'math',
      key: 'math',
      width: 80,
      sorter: queryType === 'class' ? createSorter('math') : false,
      render: (val) => val || '-'
    },
    {
      title: '英语',
      dataIndex: 'english',
      key: 'english',
      width: 80,
      sorter: queryType === 'class' ? createSorter('english') : false,
      render: (val) => val || '-'
    },
    {
      title: '物理',
      dataIndex: 'physics',
      key: 'physics',
      width: 80,
      sorter: queryType === 'class' ? createSorter('physics') : false,
      render: (val) => val || '-'
    },
    {
      title: '化学',
      dataIndex: 'chemistry',
      key: 'chemistry',
      width: 80,
      sorter: queryType === 'class' ? createSorter('chemistry') : false,
      render: (val) => val || '-'
    },
    {
      title: '生物',
      dataIndex: 'biology',
      key: 'biology',
      width: 80,
      sorter: queryType === 'class' ? createSorter('biology') : false,
      render: (val) => val || '-'
    },
    {
      title: '政治',
      dataIndex: 'politics',
      key: 'politics',
      width: 80,
      sorter: queryType === 'class' ? createSorter('politics') : false,
      render: (val) => val || '-'
    },
    {
      title: '历史',
      dataIndex: 'history',
      key: 'history',
      width: 80,
      sorter: queryType === 'class' ? createSorter('history') : false,
      render: (val) => val || '-'
    },
    {
      title: '地理',
      dataIndex: 'geography',
      key: 'geography',
      width: 80,
      sorter: queryType === 'class' ? createSorter('geography') : false,
      render: (val) => val || '-'
    },
    {
      title: '总分',
      dataIndex: 'totalScore',
      key: 'totalScore',
      width: 100,
      sorter: queryType === 'class' ? createSorter('totalScore') : false,
      render: (val) => val || '-'
    },
    {
      title: '校次',
      dataIndex: 'schoolRank',
      key: 'schoolRank',
      width: 80,
      sorter: queryType === 'class' ? createSorter('schoolRank') : false,
      render: (val) => val || '-'
    }
  ];

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      padding: '40px 20px'
    }}>
      <Card
        style={{
          maxWidth: 1400,
          margin: '0 auto',
          borderRadius: '12px',
          boxShadow: '0 4px 20px rgba(0,0,0,0.1)'
        }}
      >
        <div style={{ textAlign: 'center', marginBottom: 30 }}>
          <h1 style={{ fontSize: '28px', color: '#333', marginBottom: 8 }}>
            学生成绩查询系统
          </h1>
          <p style={{ color: '#666', fontSize: '14px' }}>
            {queryType === 'name' 
              ? '请输入姓名查询成绩，如有重名会显示所有同名学生的成绩' 
              : '请输入班级名称查询该班级所有学生的成绩（支持简写，如输入"1"代表"高一年级1班"）'}
          </p>
        </div>

        <div style={{ textAlign: 'center', marginBottom: 20 }}>
          <Button.Group size="large">
            <Button
              type={queryType === 'name' ? 'primary' : 'default'}
              onClick={() => {
                setQueryType('name');
                form.resetFields();
                setData([]);
                setSearched(false);
              }}
            >
              按姓名查询
            </Button>
            <Button
              type={queryType === 'class' ? 'primary' : 'default'}
              onClick={() => {
                setQueryType('class');
                form.resetFields();
                setData([]);
                setSearched(false);
              }}
            >
              按班级查询
            </Button>
          </Button.Group>
        </div>

        <Form
          form={form}
          layout="inline"
          style={{ marginBottom: 24, justifyContent: 'center' }}
          onFinish={handleSearch}
        >
          <Form.Item
            name="searchValue"
            rules={[{ 
              required: true, 
              message: queryType === 'name' ? '请输入姓名' : '请输入班级名称' 
            }]}
          >
            <Input
              placeholder={queryType === 'name' ? '请输入姓名' : '请输入班级名称（如：1 或 高一年级1班）'}
              size="large"
              style={{ width: 350 }}
              onPressEnter={handleSearch}
            />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              icon={<SearchOutlined />}
              onClick={handleSearch}
              loading={loading}
              size="large"
            >
              查询成绩
            </Button>
          </Form.Item>
        </Form>

        {searched && (
          data.length > 0 ? (
            <>
              <div style={{ marginBottom: 16, color: '#666' }}>
                找到 <strong style={{ color: '#1890ff' }}>{data.length}</strong> 条成绩记录
                {queryType === 'name' && (
                  <span style={{ marginLeft: 16, fontSize: '13px', color: '#52c41a' }}>
                    <RobotOutlined /> 点击学生姓名可查看AI智能分析
                  </span>
                )}
                {queryType === 'class' && (
                  <span style={{ marginLeft: 16, fontSize: '13px' }}>
                    （点击学生姓名查看该学生所有成绩，点击学科名称可排序）
                  </span>
                )}
              </div>
              
              {queryType === 'class' && Object.keys(averages).length > 0 && (
                <div style={{
                  marginBottom: 16,
                  padding: '12px 16px',
                  background: '#f0f7ff',
                  borderRadius: '6px',
                  border: '1px solid #d6e4ff'
                }}>
                  <div style={{ fontWeight: 'bold', marginBottom: 8, color: '#1890ff' }}>
                    各科平均分：
                  </div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: '12px', fontSize: '13px' }}>
                    <span>语文: <strong>{averages.chinese}</strong></span>
                    <span>数学: <strong>{averages.math}</strong></span>
                    <span>英语: <strong>{averages.english}</strong></span>
                    <span>物理: <strong>{averages.physics}</strong></span>
                    <span>化学: <strong>{averages.chemistry}</strong></span>
                    <span>生物: <strong>{averages.biology}</strong></span>
                    <span>政治: <strong>{averages.politics}</strong></span>
                    <span>历史: <strong>{averages.history}</strong></span>
                    <span>地理: <strong>{averages.geography}</strong></span>
                    <span style={{ color: '#1890ff', fontWeight: 'bold' }}>
                      总分: <strong>{averages.totalScore}</strong>
                    </span>
                  </div>
                </div>
              )}
              
              <Table
                columns={columns}
                dataSource={data}
                rowKey="id"
                loading={loading}
                pagination={false}
                scroll={{ x: 1500 }}
                bordered
              />
            </>
          ) : (
            <Empty
              description="未找到相关成绩记录"
              style={{ padding: '60px 0' }}
            />
          )
        )}

        {/* AI 分析报告弹窗 */}
        <Modal
          title={
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <RobotOutlined style={{ color: '#1890ff', fontSize: '20px' }} />
                <span>AI 智能成绩分析报告</span>
                {currentStudent && (
                  <span style={{ fontSize: '14px', color: '#666', fontWeight: 'normal' }}>
                    - {currentStudent.name} ({currentStudent.className})
                  </span>
                )}
              </div>
              {!analysisLoading && analysisReport && (
                <div style={{ display: 'flex', gap: '8px' }}>
                  {isEditing ? (
                    <>
                      <Button
                        size="small"
                        icon={<SaveOutlined />}
                        type="primary"
                        onClick={handleSaveReport}
                        loading={analysisLoading}
                      >
                        保存
                      </Button>
                      <Button
                        size="small"
                        icon={<CloseOutlined />}
                        onClick={() => {
                          setIsEditing(false);
                          setEditedReport(analysisReport);
                        }}
                      >
                        取消
                      </Button>
                    </>
                  ) : (
                    <Button
                      size="small"
                      icon={<EditOutlined />}
                      onClick={() => {
                        setIsEditing(true);
                        setEditedReport(analysisReport);
                      }}
                    >
                      编辑
                    </Button>
                  )}
                </div>
              )}
            </div>
          }
          open={analysisModalVisible}
          onCancel={() => setAnalysisModalVisible(false)}
          footer={null}
          width={900}
          style={{ top: 20 }}
          bodyStyle={{ maxHeight: '70vh', overflow: 'auto' }}
        >
          <div>
              {reportFromCache && reportCachedAt && !isEditing && (
                <div style={{
                  padding: '12px 20px',
                  background: '#e6f7ff',
                  borderBottom: '1px solid #91d5ff',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between'
                }}>
                  <span style={{ color: '#0050b3', fontSize: '13px' }}>
                    📋 此报告来自缓存（生成于 {new Date(reportCachedAt).toLocaleString('zh-CN')}）
                  </span>
                  <span style={{ color: '#666', fontSize: '12px' }}>
                    点击右上角"编辑"按钮可修改报告内容
                  </span>
                </div>
              )}
              
              {isEditing ? (
                <div style={{ padding: '20px' }}>
                  <div style={{ marginBottom: '12px', color: '#666', fontSize: '13px' }}>
                    💡 提示：支持 Markdown 格式，编辑后点击"保存"按钮
                  </div>
                  <TextArea
                    value={editedReport}
                    onChange={(e) => setEditedReport(e.target.value)}
                    rows={20}
                    style={{ 
                      fontFamily: 'monospace',
                      fontSize: '14px',
                      lineHeight: '1.6'
                    }}
                  />
                </div>
              ) : (
                <>
                  <div 
                    ref={reportContentRef}
                    style={{ 
                      padding: '20px',
                      lineHeight: '1.8',
                      fontSize: '15px'
                    }}
                  >
                    <ReactMarkdown
                    components={{
                      h1: ({node, ...props}) => (
                        <h1 style={{ 
                          color: '#1890ff', 
                          borderBottom: '3px solid #1890ff', 
                          paddingBottom: '12px',
                          marginBottom: '20px',
                          fontSize: '24px'
                        }} {...props} />
                      ),
                      h2: ({node, ...props}) => (
                        <h2 style={{ 
                          color: '#52c41a', 
                          marginTop: '32px',
                          marginBottom: '16px',
                          fontSize: '20px',
                          borderLeft: '4px solid #52c41a',
                          paddingLeft: '12px'
                        }} {...props} />
                      ),
                      h3: ({node, ...props}) => (
                        <h3 style={{ 
                          color: '#faad14', 
                          marginTop: '24px',
                          marginBottom: '12px',
                          fontSize: '18px'
                        }} {...props} />
                      ),
                      p: ({node, ...props}) => (
                        <p style={{ 
                          marginBottom: '12px',
                          textAlign: 'justify'
                        }} {...props} />
                      ),
                      ul: ({node, ...props}) => (
                        <ul style={{ 
                          paddingLeft: '24px',
                          marginBottom: '16px'
                        }} {...props} />
                      ),
                      ol: ({node, ...props}) => (
                        <ol style={{ 
                          paddingLeft: '24px',
                          marginBottom: '16px'
                        }} {...props} />
                      ),
                      li: ({node, ...props}) => (
                        <li style={{ 
                          marginBottom: '8px',
                          lineHeight: '1.8'
                        }} {...props} />
                      ),
                      strong: ({node, ...props}) => (
                        <strong style={{ 
                          color: '#1890ff',
                          fontWeight: 600
                        }} {...props} />
                      ),
                      table: ({node, ...props}) => (
                        <div style={{ 
                          overflowX: 'auto',
                          margin: '20px 0',
                          boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
                          borderRadius: '8px'
                        }}>
                          <table style={{ 
                            width: '100%', 
                            borderCollapse: 'separate',
                            borderSpacing: 0,
                            border: '1px solid #e8e8e8',
                            borderRadius: '8px',
                            overflow: 'hidden'
                          }} {...props} />
                        </div>
                      ),
                      thead: ({node, ...props}) => (
                        <thead style={{
                          background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
                        }} {...props} />
                      ),
                      th: ({node, ...props}) => (
                        <th style={{ 
                          border: 'none',
                          padding: '14px 12px',
                          color: '#fff',
                          fontWeight: 600,
                          textAlign: 'center',
                          fontSize: '14px',
                          borderRight: '1px solid rgba(255,255,255,0.2)'
                        }} {...props} />
                      ),
                      tbody: ({node, ...props}) => (
                        <tbody {...props} />
                      ),
                      tr: ({node, ...props}) => (
                        <tr style={{
                          background: '#fff',
                          transition: 'background 0.3s'
                        }} 
                        onMouseEnter={(e) => e.currentTarget.style.background = '#f5f5f5'}
                        onMouseLeave={(e) => e.currentTarget.style.background = '#fff'}
                        {...props} />
                      ),
                      td: ({node, ...props}) => (
                        <td style={{ 
                          border: 'none',
                          borderBottom: '1px solid #e8e8e8',
                          borderRight: '1px solid #e8e8e8',
                          padding: '12px',
                          textAlign: 'center',
                          fontSize: '14px'
                        }} {...props} />
                      ),
                      blockquote: ({node, ...props}) => (
                        <blockquote style={{
                          borderLeft: '4px solid #1890ff',
                          paddingLeft: '16px',
                          margin: '16px 0',
                          color: '#666',
                          background: '#f0f7ff',
                          padding: '12px 16px',
                          borderRadius: '4px'
                        }} {...props} />
                      ),
                      code: ({node, inline, ...props}) => 
                        inline ? (
                          <code style={{
                            background: '#f5f5f5',
                            padding: '2px 6px',
                            borderRadius: '3px',
                            fontSize: '13px',
                            color: '#d63384'
                          }} {...props} />
                        ) : (
                          <code style={{
                            display: 'block',
                            background: '#f5f5f5',
                            padding: '12px',
                            borderRadius: '6px',
                            fontSize: '13px',
                            overflowX: 'auto',
                            margin: '12px 0'
                          }} {...props} />
                        )
                    }}
                  >
                    {analysisReport}
                  </ReactMarkdown>
                </div>
                  
                {/* 导出PDF按钮 */}
                  <div style={{ 
                    padding: '20px',
                    borderTop: '1px solid #e8e8e8',
                    textAlign: 'center'
                  }}>
                    <Button
                      type="primary"
                      icon={<FileWordOutlined />}
                      onClick={handleExportWord}
                      loading={exportingPdf}
                      size="large"
                      style={{
                        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                        border: 'none',
                        boxShadow: '0 2px 8px rgba(102, 126, 234, 0.3)'
                      }}
                    >
                      {exportingPdf ? '正在生成Word...' : '导出Word报告'}
                    </Button>
                </div>
              </>
            )}
            
            {/* 流式生成时的加载提示 */}
            {analysisLoading && analysisReport && (
              <div style={{
                padding: '12px 20px',
                background: '#f0f7ff',
                borderTop: '1px solid #d6e4ff',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                gap: '12px'
              }}>
                <Spin size="small" />
                <span style={{ color: '#1890ff', fontSize: '13px' }}>
                  正在生成中，内容实时更新...
                </span>
              </div>
            )}
            
            {/* 初始加载提示（还没有任何内容时） */}
            {analysisLoading && !analysisReport && (
              <div style={{ textAlign: 'center', padding: '60px 0' }}>
                <Spin size="large" />
                <p style={{ marginTop: 16, color: '#666', fontSize: '15px' }}>
                  AI 正在深度分析成绩数据...
                </p>
                <p style={{ marginTop: 8, color: '#999', fontSize: '13px' }}>
                  报告内容将实时显示，请稍候
                </p>
                <p style={{ marginTop: 8, color: '#999', fontSize: '12px' }}>
                  💡 首次生成需要较长时间，后续查看将使用缓存，速度更快
                </p>
              </div>
            )}
          </div>
        </Modal>

      </Card>
    </div>
  );
};

export default StudentQueryPage;
